package m2st.doxia.macro;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.maven.doxia.macro.AbstractMacro;
import org.apache.maven.doxia.macro.Macro;
import org.apache.maven.doxia.macro.MacroRequest;

/**
 * Base class for custom {@link Macro} implementations.
 * 
 * @see AbstractMacro
 * @see Macro
 * 
 * @author milan.skuhra
 * @author vojtech.szocs
 */
public abstract class BaseMacro extends AbstractMacro {

    /**
     * Returns a {@link URL} for the resource location specified
     * either by <tt>urlParamName</tt> or <tt>fileParamName</tt>
     * {@link MacroRequest} parameters.
     * 
     * <p>
     * 
     * Note that the <tt>urlParamName</tt> parameter always takes
     * precedence over the <tt>fileParamName</tt> when searching
     * for the resource location.
     * 
     * @param request {@link MacroRequest} instance containing
     * appropriate resource location parameter(s).
     * @return Corresponding resource {@link URL}.
     */
    protected URL getResourceUrl(MacroRequest request, String urlParamName, String fileParamName) {
        String url = (String) request.getParameter(urlParamName);
        String file = (String) request.getParameter(fileParamName);
        
        if (url != null) {
            try {
                return new URL(url);
            } catch (MalformedURLException e) {
                throw new IllegalArgumentException("Malformed URL " + url);
            }
        }
        
        else if (file != null) {
            File f = new File(file);
            
            if (!f.isAbsolute())
                f = new File(request.getBasedir(), file);
            
            try {
                return f.toURL();
            } catch (MalformedURLException e) {
                throw new IllegalArgumentException("Malformed URL for file " + file);
            }
        }
        
        else {
            throw new IllegalArgumentException("Either '" + urlParamName + "' or '"
                    + fileParamName + "' macro parameter needs to be specified");
        }
    }
    
}
